package com.itqf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itqf.entity.TbItem;
import com.itqf.mapper.TbItemMapper;
import com.itqf.service.TbItemService;
import com.itqf.utils.R;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/22
 * @Time: 下午3:04
 */
@Service
public class TbItemServiceImpl implements TbItemService {

    @Resource //默认按照名注入
    private TbItemMapper tbItemMapper;

    //日志  分析程序的运行流程
    private Logger logger = Logger.getLogger(TbItemServiceImpl.class);



    @Override
    public List<TbItem> findAll() {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");//降序排序

        return tbItemMapper.selectList(queryWrapper);
    }

    @Transactional(readOnly = false,isolation = Isolation.DEFAULT)
    @Override
    public int addTbItem(TbItem tbItem) {

        logger.info("【新增商品】"+tbItem);

        return tbItemMapper.insert(tbItem);
    }

    @Override
    public TbItem findById(long id) {
        String s = null;

        return tbItemMapper.selectById(id);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        return tbItemMapper.deleteBatchIds(ids);//mybatis-plus
    }

    @Override
    public int update(TbItem tbItem) {
        return tbItemMapper.updateById(tbItem);
    }


    @Override
    public R findByPage(int page, int limit) {
        IPage iPage = new Page();
        iPage.setCurrent(page);//当前页
        iPage.setSize(limit);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");

        iPage = tbItemMapper.selectPage(iPage,queryWrapper);

        List<TbItem> list = iPage.getRecords();
        long total  = iPage.getTotal();
        //总的记录数  总的页数
        /**
         * {"msg":"no data",
         *   "code":0,
         *   "data":[{"id":1,"username":"shine1","sex":"男","city":"保定","score":100},
         *     {"id":2,"username":"shine2","sex":"女","city":"石家庄","score":100},
         *     {"id":3,"username":"shine3","sex":"男","city":"邢台","score":100}],
         *   "count":100}
         */


        return R.ok("数据").put("data",list).put("count",total);
    }

    @Override
    public R del(long id) {
        int i = tbItemMapper.deleteById(id);
        return i>0?R.ok("删除成功"):R.error("删除失败");
    }

    @Override
    public R updateTbItem(TbItem tbItem) {
        int i = tbItemMapper.updateById(tbItem);
        return i>0?R.ok("修改成功过"):R.error("修改失败");
    }
}
